define(function(require,exports,module) {
    var billDateUrl = '/GroupBuying/orderListForIndex';  // 模拟数据
    var oErrPage = $('.js_errPage');                     // 没有数据时错误页面
    var oCotain = $('.js_cotain');                       // 内容页面
    var oLoadingNull = $('.js_loadingBtn').eq(0);        // 没有更多了按钮
    var oLoading = $('.js_loadingBtn').eq(1);            // 加载中
    var oScroll = $('.js_scroll');                       // 滚动部分
    var ordersListBox = $('.js_cotain ul');
    // 获取当前链接的后缀
    var domain = window.location.host;
    var oUrl = window.location.href;
    var nLength = domain.length;
    var nIndex = oUrl.indexOf(domain);
    var useFull = oUrl.substring(nIndex+nLength);
    module.exports = {
        init: function() {
            connectHtml.AjaxData(connectHtml.start, connectHtml.pageSize);
            connectHtml.ScrollPage();
        }
    };
    var connectHtml = {
        pageSize: 10,                    // 每次加载多少数据
        getData: [],                    // 数据记录
        pageIndex: 1,                   // 当前页码
        pageCout: 0,                    // 页码总数
        start:0,                        // 开始数据
        end: 0,                         // 结束数据
        time_Scroll:null,               // 计时器
        bLoadOff: true,                 // 加载开关
        // 设置广告数据
        AjaxData: function (start, end , fn) {
            var _this = this;
            G_JSON_POST(billDateUrl,{
                'pageIndex': _this.pageIndex,
                'pageSize': _this.pageSize,
                'start': _this.start,
                'end': _this.end
            },function (data) {
                if( data.message == "login") {
                    _this.setCookie('historyLastUrl',useFull);
                    window.location.href = "/h/login/";
                }
                if( data.message == "bind") {
                    window.location.href = "/h/login/bindMobile?backHref="+useFull;
                }
                if( data.message == "error") {
                    oCotain.hide();
                    oErrPage.show();
                    return false;
                }
                // 存储数据
                _this.getData = data.result;
                if( data.message == "success") {
                    // 没有数据和页数1页时候 显示错误页面
                    if(_this.getData.length == 0 && _this.pageIndex < 2) {
                        _this.bLoadOff = false;
                        oCotain.hide();
                        oErrPage.show();
                        return
                    }
                    // 页数大于
                    if( _this.pageIndex >=1) {
                        if( _this.getData.length == 0) {
                            oLoading.hide();
                            oLoadingNull.show();
                            _this.bLoadOff = false;
                            return
                        }

                    }

                    // 拼接页面
                    _this.GoodsLiBoxHtml(_this.getData);
                    oLoading.show();

                    if(_this.getData.length <  _this.pageSize) {
                        oLoading.hide();
                        oLoadingNull.show();
                        _this.bLoadOff = false;
                    }
                    data = null;
                    if(fn)fn();
                }
            }, function () {
                // start
            }, function () {
                // end
            });
        },
        ScrollPage: function () {
            var _this = this;
            var minScrHeight = 200;

            oScroll.on('scroll', function () {
                var afterScroll = $(this).scrollTop();

                // 滚动页面距离底部200像素 延迟250毫秒加载数据
                clearTimeout(_this.time_Scroll);
                _this.time_Scroll = setTimeout(function() {
                    if(oCotain[0].scrollHeight - afterScroll - oScroll.height() < minScrHeight) {
                        // 设置翻页到最后一页 返回
                        if(!_this.bLoadOff) {
                            _this.dataJson = null;
                            return;
                        }

                        // console.log( _this.pagearr)
                        // 滚动底部页数增加 起始数据等于上次结束数据  新的结束等于页数*页码数
                        _this.start = _this.pageSize*_this.pageIndex;
                        _this.pageIndex++;
                        _this.AjaxData(_this.start, _this.pageSize);
                    }
                },250);
            })

        },

        // 正常的数据
        GoodsLiBoxHtml : function (data, fn) {
            var _this = this;
            var shtml = '';
            for (var i=0; i<data.length; i++) {
                shtml +='<li>'+
                             '<a href="/h/tuangou/groupOrderDetail/'+data[i].recordId+'?goodsSn='+data[i].goodsSn+'">'+
                                '<div class="img">'+
                                '<img class="img_cover" src="'+ sUrl+data[i].goodsImg +'?x-oss-process=style/goods_img" />'+
                                '</div>'+
                                '<div class="text">'+
                                '<div class="name nowrap">'+data[i].goodsName+'</div>'+
                                '<div class="price2">¥'+data[i].paidAmount+'<span class="fr gray size22">*'+data[i].quantity+'</span></div>'+
                                '<div class="peo">'+data[i].tuangouCount+'人团<span class="fr red">';
                               if (data[i].recordStatus==0){
                                   shtml += ' 待成团'
                               }else if(data[i].recordStatus==1){
                                   shtml += '拼单成功'
                               }else if(data[i].recordStatus==2){
                                   shtml +=  '拼单失败'
                               }else if(data[i].recordStatus==3){
                                   shtml +=  ' 拼单成功'
                               }else if(data[i].recordStatus==4){
                                   shtml +=  ' 等待开奖'
                               }else if(data[i].recordStatus==5){
                                   if(data[i].awardLevel==0){
                                       shtml +=  ' 未中奖'
                                   }else{
                                       shtml +=  data[i].levelName
                                   }
                               }
                            shtml += '</span></div>'+
                                '</div>'+
                                '<div class="clear"></div>'+
                            '</a>'+
                            '<div class="bottom_bt">';
                               if(data[i].recordStatus==0){
                                   shtml += '<div class="orderLeftTime HBox BoxCenter js_orderListTime">'+
                                       '<input type="hidden" class="createTime" value="'+data[i].recordCreateTime+'">'+
                                       '<input type="hidden" class="activityEndTimeStamp" value="'+data[i].activityEndTime+'">'+
                                       '<p style="display: inline-block">离结束还剩: <span><em class="hours">00</em>:<em class="minutes">00</em>:<em class="seconds">00</em></span></p>'+
                                       '</div>'+
                                       '<a href="/h/tuangou/groupOrderDetail/'+data[i].recordId+'?goodsSn='+data[i].goodsSn+'"><button class="btn_gray">立即邀请</button></a>'
                               }
                               if(data[i].recordStatus==1 ||data[i].recordStatus==3 || ( data[i].recordStatus==5 && data[i].awardLevel == 1)){
                                    shtml += '   <a href="/shop/pay/order_view?orderSn='+data[i].orderSn+'"><button class="btn_gray">订单详情</button></a>'
                               }
                            shtml += '</div>'+
                        '</li>'
            }
            var oshtml = $(shtml);
            ordersListBox.append(oshtml);
            // 高度检测
            if(ordersListBox.height() < oScroll.height()) {
                //console.log('不够高度');
                _this.start = _this.pageSize*_this.pageIndex;
                _this.pageIndex++;
                _this.AjaxData(_this.start, _this.pageSize);
            }

            // 拼单订单倒计时
            if($('.js_orderListTime')){
                startCounterForOrderList();
                //拼单订单列表倒计时
                function startCounterForOrderList() {
                    var createTimes = [];
                    var activityEndTimeStamps = [];
                    var endTimes = [];
                    var $jsTime = $('.js_orderListTime');

                    $jsTime.each(function (i) {
                        createTimes[i] = Math.round( $jsTime.eq(i).find(".createTime").val() / 1000);
                        activityEndTimeStamps[i] =Math.round( $jsTime.eq(i).find(".activityEndTimeStamp").val() / 1000) ;
                        endTimes[i] = createTimes[i]+24 * 3600;
                        if( endTimes[i] > activityEndTimeStamps[i] ){
                            endTimes[i] = activityEndTimeStamps[i];//如果普通情况结束时间大于活动结束时间,说明该团在24小时之前就已经结束,取活动结束时间为最终时间
                        }
                    });
                    setInterval(function () {
                        var currentTime = Math.round(new Date().getTime() / 1000);
                        for (var i=0; i<$jsTime.length; i++) {
                            var hours = timeStamp2Datetime(endTimes[i] - currentTime, 'hours');
                            var minutes = timeStamp2Datetime(endTimes[i] - currentTime, 'minutes');
                            var seconds = timeStamp2Datetime(endTimes[i] - currentTime, 'seconds');

                            if (hours == '00' && minutes == '00' && seconds == '00') {
                                $jsTime.eq(i).hide();
                            }

                            $jsTime.eq(i).find('.hours').text(hours);
                            $jsTime.eq(i).find('.minutes').text(minutes);
                            $jsTime.eq(i).find('.seconds').text(seconds);
                        }


                    }, 1000)
                }
                function timeStamp2Datetime(spaceTimeStamp, type) {
                    if (spaceTimeStamp <= 0)
                        return '00';
                    var hours = Math.floor(spaceTimeStamp / 3600), minutes = Math.floor((spaceTimeStamp - 3600 * hours) / 60),
                        seconds = spaceTimeStamp - hours * 3600 - minutes * 60;
                    if (hours < 10)
                        hours = '0' + hours;
                    if (minutes < 10)
                        minutes = '0' + minutes;
                    if (seconds < 10)
                        seconds = '0' + seconds;
                    switch (type) {
                        case 'hours':
                            return hours;
                        case "minutes":
                            return minutes;
                        case "seconds":
                            return seconds
                    }
                }
            }
            if(fn)fn();
        },

        //设置cookie时间
        getsec:function(str){
            var str1=str.substring(1,str.length)*1;
            var str2=str.substring(0,1);
            if (str2=="s") {
                return str1*1000;
            }
            else if (str2=="h") {
                return str1*60*60*1000;
            }
            else if (str2=="d") {
                return str1*24*60*60*1000;
            }
        },
        // 保存到cookies
        setCookie:function (name,value,time) {
            var strsec;
            if (time == undefined) {
                var Days = 30; //默认30天有效期
                strsec = Days*24*60*60*1000;
            }
            else {
                strsec = getsec(time)*1;
            }
            var exp = new Date();
            exp.setTime(exp.getTime() + strsec);
            document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString() + ";path=/";
        }
    }
});